package 知识点复习.异步回调.线程池使用;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class CompletableDemo3 {
    public static void threadPoolDemo() throws Exception {
        //混合线程池
        ExecutorService pool = Executors.newFixedThreadPool(10);
        CompletableFuture<Long> future = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + ":run begin...");
            long start = System.currentTimeMillis();
            try {
                Thread.sleep(1000);//模拟执行1秒
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName() + ":run end...");
            return System.currentTimeMillis() - start;
        }, pool);

        //等待异步任务执行完成，限时等待2秒
        Long time = future.get(2, TimeUnit.SECONDS);
        System.out.println(Thread.currentThread().getName() + ":异步执行耗时(秒)：" + time / 1000);
    }

    public static void main(String[] args) throws Exception {
        threadPoolDemo();
    }
}
